package com.sf.melon.utils;


import com.sf.melon.model.Point;

import java.util.*;

/**
 * @author wujiang
 * @version 1.0.0
 * @date 2017/12/1
 * 使用伟大的无产阶级重心算法，用于确定区域的工具类
 */
public class ZoneUtils {

    public static int defineDirection(int x, int y, List<Point> pointList){
        Map<Double,Integer> resultMap = findGravityCenter(x,y,defineQuadrant(x,y,pointList));
        List<Double> list = new ArrayList<>();
            for (Double key : resultMap.keySet()) {
                list.add(key);
            }

        Collections.sort(list);
        return resultMap.get(list.get(list.size()-1));
    }

    private static Map<Integer,List<Point>> defineQuadrant(int x, int y, List<Point> pointList){
        Map<Integer,List<Point>> quadrantMap = new HashMap<>();
        List<Point> list1 = new ArrayList();
        List<Point> list2 = new ArrayList();
        List<Point> list3 = new ArrayList();
        List<Point> list4 = new ArrayList();
        for(Point p:pointList){
            int targetX = p.getX();
            int targetY = p.getY();
            if (targetX + targetY - x - y < p.getValue()){
                if (targetX >= x && targetY > y){
                    list4.add(p);
                }if (targetX < x && targetY >= y){
                    list1.add(p);
                }if (targetX <= x && targetY < y){
                    list2.add(p);
                }if (targetX > x && targetY <= y){
                    list3.add(p);
                }
            }
        }
        quadrantMap.put(1,list1);
        quadrantMap.put(2,list2);
        quadrantMap.put(3,list3);
        quadrantMap.put(4,list4);
        return quadrantMap;
    }

    private static Map<Double,Integer> findGravityCenter(int x, int y, Map<Integer,List<Point>> map){
        Map<Double,Integer> resultMap = new HashMap<>();
        for (Map.Entry<Integer, List<Point>> entry : map.entrySet()) {
            Integer i = entry.getKey();
            List<Point> list = entry.getValue();
            int size = list.size();
            if (size > 0){
                int sumX = 0;
                int sumY = 0;
                for (Point p:list){
                    sumX += p.getX()*p.getValue();
                    sumY += p.getY()*p.getValue();
                }

                double resultX = sumX/size * 1.00;
                double resultY = sumY/size * 1.00;
                resultMap.put(resultX + resultY - x - y,i);
            }

        }
        return resultMap;
    }

    public static void main(String[] args) {
        List<Double> list = new ArrayList<>();
        list.add(1.22);
        list.add(1.23);
        list.add(9.86);
        list.add(1.75);
        Collections.sort(list);
        System.out.println(list);
    }
}
